package com.motu.monstercity.server.gate;


import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.vertx.module.utility.base.ServerConfig;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.http.ServerWebSocket;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/***
 * 检查用户是否有重复登录
 * @author ibm1
 *
 */
public class CheckRepeatedLoginVerticle extends AbstractVerticle {
    public final static Logger logger = LoggerFactory.getLogger(CheckRepeatedLoginVerticle.class);

    //	  private Counter activeUserCounter;
//	  UserService userService;
//	  private  ConcurrentHashMap<Integer, ServerWebSocket> socketList = new ConcurrentHashMap<Integer, ServerWebSocket>();
    @Override
    public void start(Promise<Void> future) throws Exception {

        EventBus eb = vertx.eventBus();
        String ebName = EventBusConstant.getAddress(EventBusConstant.GATE_CHECKREPEATEDLOGIN);
        MessageConsumer<JsonObject> consumer = eb.consumer(ebName);
        logger.info("---===#*#*#*#===---* gate start  ebName:" + ebName);
        consumer.handler(message -> {

            JsonObject recData = message.body();
            String gateName = recData.getString("gatename");
            long userId = recData.getLong("userid");
            int language = recData.getInteger("language");
            if (!gateName.equalsIgnoreCase(ServerConfig.getGateName())) {
                ServerWebSocket socket = SocketManager.getSocket(userId);
                if (socket != null) {
                    logger.info("### CheckRepeatedLoginVerticle userId:" + userId);
                    SocketManager.endRepeatdLogin(userId, socket, language);
                }
            }
        });

        consumer.completionHandler(res2 -> {

            if (res2.succeeded()) {

                future.complete();
                logger.info("The CheckRepeatedLoginVerticle handler registration has reached all nodes");

            } else {

                future.fail("The CheckRepeatedLoginVerticle handler registration has failed");
                logger.error("CheckRepeatedLoginVerticle Registration failed! " + res2.cause().toString());

            }

        });

    }


}
